import React, { useState, useMemo, useCallback } from 'react'
import './style.less'
import { Button, Space, message, Popconfirm, Form, Modal, Input, Flex } from 'antd'
import {
  approveDataItemAudit,
  delistDataItem,
  onlineDataItem,
  rejectDataItemAudit,
  reqDataItemList,
  reqDeleteDataItem
} from '@/api/assetMaintain/basic/item'
import { moveUpDataProductList, moveDownDataProductList } from '@/api/assetMaintain/dataProduct'
import { EMPTYTEXT, PERMISSIONS, getItem, usePage } from '@hs-admin/utils'
import MoveSort from '@/components/global/NewMoveSort'
import { useNavigate } from 'react-router-dom'
import { HsAdminTablePage, HsAdminForm, HsAdminSpin } from '@hs-admin/base-components'
import { HsAdminSelectTheme } from '@/components/global'
import { dataItemStatus } from '@/utils/type'
import { handleDeleteListPage } from '@/hooks/useList'

const OperationBasicDataItem: React.FC = () => {
  const navigate = useNavigate()
  const permissions = getItem(PERMISSIONS) || []
  const [comment, setcomment] = useState('')
  const [checkInfo, setcheckInfo] = useState<any>({})
  const [loading, setloading] = useState(true)

  const { pagination, resetPage, setPagination }: { pagination: UsePageProps; resetPage: () => void; setPagination: (params: SetStatePage) => void } =
    usePage(callList)
  // 搜索和重置都会执行
  const handleSearch = useCallback(async () => {
    resetPage()
  }, [resetPage])
  const [form] = Form.useForm()
  const formItemOptions = useMemo(
    () => [
      {
        label: '数据项名称',
        name: 'keywords',
        component: 'Input',
        FormItemColProps: {
          span: 6
        },
        componentProps: {
          onPressEnter: handleSearch,
          placeholder: '请输入数据项名称、英文表名'
        }
      },
      {
        label: '所属主题',
        name: 'data_topic_id',
        slot: 'data_topic_id',
        FormItemColProps: {
          span: 6
        }
      },
      {
        label: '状态',
        name: 'status',
        component: 'Select',
        componentProps: {
          options: dataItemStatus(),
          onChange: handleSearch
        },
        FormItemColProps: {
          span: 6
        }
      },
      {
        slot: 'submit',
        FormItemColProps: {
          span: 6
        },
        FormItemProps: {
          labelCol: { span: 0 },
          wrapperCol: { span: 24 }
        }
      }
    ],
    [handleSearch]
  )

  const moveUp = (record: any) => {
    moveUpDataProductList({ id: record.id, tags: ['数据项产品'] }).then(() => {
      message.success('上移成功')
      callList()
    })
  }
  const moveDown = (record: any) => {
    moveDownDataProductList({ id: record.id, tags: ['数据项产品'] }).then(() => {
      message.success('下移成功')
      callList()
    })
  }
  const columns = [
    {
      title: '移动',
      width: 80,
      render: (_: any, record: any, index: number) => (
        <MoveSort pagination={pagination} record={record} index={index} data={data} moveUp={moveUp} moveDown={moveDown} />
      )
    },
    {
      title: '数据项名称',
      dataIndex: 'name',
      width: 245
    },
    {
      title: '英文表名',
      dataIndex: 'ref_table_name'
    },
    {
      title: '数据项描述',
      dataIndex: 'description',
      width: 200,
      ellipsis: true
    },
    {
      title: '所属主题',
      dataIndex: 'data_topics',
      render: (_: any, record: any) => (
        <span>{record.data_topics?.length ? record.data_topics.map((item: any) => item.name).join(',') : EMPTYTEXT}</span>
      )
    },
    {
      title: '最新维护人',
      dataIndex: 'owner.name'
    },
    {
      title: '最新维护时间',
      dataIndex: 'updated_at',
      type: 'datetime'
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 80,
      render: (_: any, record: any) => {
        return dataItemStatus(record.status)
      }
    },
    {
      title: '操作',
      key: 'actions',
      width: 200,
      fixed: 'right',
      render: (_: any, record: any) => {
        return actionCompute(record)
      }
    }
  ]
  const actionCompute = (record: any) => (
    <>
      {permissions.includes('datashop.data_item.update') && (
        <Button type="link" size="small" onClick={() => callDetail(record)}>
          编辑
        </Button>
      )}
      {permissions.includes('datashop.data_item.disable') && record.status === 'published' && (
        <Button
          type="link"
          size="small"
          onClick={async () => {
            pullDataItem(record)
          }}>
          下架
        </Button>
      )}
      {permissions.includes('datashop.data_item.enable') && record.status === 'draft' && (
        <Button
          type="link"
          size="small"
          onClick={async () => {
            pushDataItem(record)
          }}>
          上架
        </Button>
      )}
      {permissions.includes('datashop.data_item.delete') && (record.status === 'draft' || record.status === 'rejected') && (
        <Popconfirm title="警告" description="确定删除该项吗?" onConfirm={() => deleteDataItem(record)}>
          <Button type="link" size="small">
            删除
          </Button>
        </Popconfirm>
      )}
      {permissions.includes('datashop.data_item.audit') && record.status === 'wait_for_audit' && (
        <Popconfirm
          title="数据项上架审批"
          description="是否审批通过并上架?"
          onConfirm={() => passClick(record)}
          onCancel={() => {
            setcheckInfo(record)
            setcomment('')
            setIsModalOpen(true)
          }}
          okText="通过"
          cancelText="驳回">
          <Button type="link" size="small">
            审批
          </Button>
        </Popconfirm>
      )}
      {permissions.includes('datashop.data_item.enable') && record.status === 'rejected' && (
        <Button
          type="link"
          size="small"
          onClick={async () => {
            pushDataItem(record)
          }}>
          上架
        </Button>
      )}
      {record.status === 'rejected' && (
        <Button
          type="link"
          size="small"
          onClick={async () => {
            setcheckInfo(record)
            setRejectTextModal(true)
          }}>
          驳回理由
        </Button>
      )}
    </>
  )
  const [data, setData] = useState<any[]>([])
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [rejectTextModal, setRejectTextModal] = useState(false)

  // 详情
  function callDetail(record: any) {
    navigate(`/operationBasic/itemDetail?id=${record.id || ''}`)
  }
  // 重置
  const reset = () => {
    form.resetFields()
    resetPage()
  }
  // 列表查询事件
  async function callList() {
    setloading(true)
    const fieldsValue = form.getFieldsValue()
    const params = {
      page: pagination.current,
      page_size: pagination.pageSize,
      ...fieldsValue
    }
    const res = await reqDataItemList(params)
    setData(res.items)
    setloading(false)
    handleDeleteListPage(pagination, res, setPagination)
    return res
  }
  // 上架
  const pushDataItem = async (record: any) => {
    await onlineDataItem({ data_product_id: record.id })
    message.success('上架成功')
    callList()
  }
  // 下架
  const pullDataItem = async (record: any) => {
    await delistDataItem({ id: record.id })
    message.success('下架成功')
    callList()
  }
  // 审批驳回的回调
  const rejectClick = async () => {
    await rejectDataItemAudit({ id: checkInfo.latest_audit?.id, message: comment })
    message.success('已驳回')
    rejectCancel()
    callList()
  }
  // 驳回取消
  const rejectCancel = async () => {
    setcomment('')
    setcheckInfo({})
    setIsModalOpen(false)
    setRejectTextModal(false)
  }
  // 审批通过的回调
  const passClick = async (record: any) => {
    await approveDataItemAudit({ id: record.latest_audit?.id })
    message.success('审批通过')
    callList()
  }
  // 删除数据项
  const deleteDataItem = (record: any) => {
    reqDeleteDataItem({ id: record.id }).then(() => {
      message.success('删除成功!')
      callList()
    })
  }

  return (
    <div className="dataItem">
      {loading && <HsAdminSpin />}
      <HsAdminForm form={form} formItemOptions={formItemOptions}>
        <div slot="data_topic_id">
          <HsAdminSelectTheme placeholder="请选择所属主题" onChange={handleSearch}></HsAdminSelectTheme>
        </div>
        <div slot="submit">
          <Flex align="center" justify="space-between">
            <Space className="ml-2">
              <Button onClick={reset}>重置</Button>
              <Button type="primary" onClick={handleSearch}>
                查询
              </Button>
            </Space>
            {permissions.includes('datashop.data_item.create') && (
              <Button type="primary" onClick={callDetail}>
                新增数据项
              </Button>
            )}
          </Flex>
        </div>
      </HsAdminForm>
      <HsAdminTablePage columns={columns} rowKey="id" dataSource={data} pagination={pagination} size="small"></HsAdminTablePage>
      <Modal
        title="输入驳回理由"
        open={isModalOpen}
        onOk={rejectClick}
        onCancel={rejectCancel}
        footer={[
          <Button key="test" type="primary" onClick={rejectCancel}>
            取消
          </Button>,
          <Button key="submit" type="primary" onClick={rejectClick}>
            确认
          </Button>
        ]}>
        <Input.TextArea value={comment} placeholder="请输入驳回理由" autoSize onChange={(e) => setcomment(e.target.value)} />
      </Modal>
      <Modal title="驳回理由" open={rejectTextModal} onCancel={rejectCancel} footer={null}>
        <p>{checkInfo.latest_audit?.comment}</p>
      </Modal>
    </div>
  )
}

export default OperationBasicDataItem
